import { AxiosRequestConfig } from 'axios'
import { UnwrapRef, ref, reactive, watch } from 'vue'
import { PageInfo } from '@/composables/models'
import { SortEnum, DefaultSearchParams } from '@/constants'
import { cleanProperties, copyProperties } from '@/utils/object-utils'
import { request } from '@/utils/request-utils'
import common from './common'

export function handleSortChange(sortParams: UnwrapRef<any>, defaultSortParams: any, afterSort: () => any) {
    return (states: any) => {
        const { prop, order } = states
        cleanProperties(sortParams)
        if (prop && order) {
            sortParams[prop + "Sort"] = order === 'ascending' ? SortEnum.ASC : SortEnum.DESC;
        } else {
            copyProperties(sortParams, defaultSortParams)
        }
        afterSort();
    }
}

export function listSearch(listRequestConfig: AxiosRequestConfig, searchParams: UnwrapRef<any>, sortParams: UnwrapRef<any>, convertList: (list: any[]) => any[] = (list: any[]) => list) {
    const dataList = ref<any[]>([])
    const search = () => {
        request({ ...listRequestConfig, params: { ...searchParams, ...sortParams } }).then(response => {
            dataList.value = convertList(response)
        })
    }

    return {
        dataList,
        search
    }
}

export function pageListSearch(pageListRequestConfig: AxiosRequestConfig, searchParams: UnwrapRef<any>, sortParams: UnwrapRef<any>, convertList: (list: any[]) => any[] = (list: any[]) => list) {
    const dataPageList = reactive<PageInfo>(common.getDefaultPageInfo())
    const pageNum = ref(DefaultSearchParams.defaultPageNum)
    const pageSize = ref(DefaultSearchParams.defaultPageSize)
    const search = () => {
        request({ ...pageListRequestConfig, params: { ...searchParams, ...sortParams, pageNum: pageNum.value, pageSize: pageSize.value } }).then(response => {
            dataPageList.list = convertList(response.list)
            dataPageList.total = response.total
            dataPageList.pageNum = response.pageNum
            dataPageList.pageSize = response.pageSize
        })
    }
    watch(pageSize, () => {
        pageNum.value = DefaultSearchParams.defaultPageNum
        search()
    })
    watch(pageNum, search)
    return {
        pageNum,
        pageSize,
        dataPageList,
        search
    }
}
